package com.data.deal.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.data.deal.entity.*;
import com.data.deal.mapper.*;
import com.data.deal.service.DataDealService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DataDealServiceImpl implements DataDealService {

    @Autowired(required = false)
    private GhostSaProMapper ghostSaProMapper;

    @Autowired(required = false)
    private GhostSaPro2Mapper ghostSaPro2Mapper;

    @Autowired(required = false)
    private GhostSaProPgMapper ghostSaProPgMapper;

    @Autowired(required = false)
    private GhostSaProDevicePgMapper ghostSaProDevicePgMapper;

    @Autowired(required = false)
    private GhostSaProDeviceMapper ghostSaProDeviceMapper;

    @Autowired
    private GhostSaProAllJsonMapper ghostSaProAllJsonMapper;

    @Autowired
    private GhostSaProAllJson2Mapper ghostSaProAllJson2Mapper;

    @Value("${sync.time:}")
    private String listTime;

    @Override
    public JSONObject dealData() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 200);
        jsonObject.put("msg", "success");
        QueryWrapper<GhostSaPro> queryWrapper = new QueryWrapper<>();
        queryWrapper.last("limit 10");
        jsonObject.put("dataMysql", ghostSaProMapper.selectList(queryWrapper));
        jsonObject.put("dataPg", ghostSaProPgMapper.selectList(queryWrapper));
        return jsonObject;
    }

    @Override
    public void moveGhostSaProData() {
        if (!listTime.isEmpty()) {
            String[] split = listTime.split(",");
            List<String> list = Arrays.asList(split);
            synccData(list);
        } else {
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String localDateTime = LocalDateTime.now().minusDays(1).format(df);
            try {
                synccData(Arrays.asList(localDateTime));
            } catch (Exception e) {
                log.error(e.getMessage());
            }
            try {
                syncc2Data(Arrays.asList(localDateTime));
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
    }


    public void syncc2Data(List<String> lt) {
        for (String localDateTime : lt) {
            Page<GhostSaPro2> ghostSaProList = PageHelper.startPage(1, 1000);
            ghostSaProList = ghostSaPro2Mapper.getGhostSaProList(localDateTime);
            PageInfo<GhostSaPro2> pages = new PageInfo<>(ghostSaProList);
            int pages1 = pages.getPages();
            for (int i = 1; i <= pages1; i++) {
                Page<GhostSaPro2> ghostSaProList1 = PageHelper.startPage(i, 1000);
                ghostSaProList1 = ghostSaPro2Mapper.getGhostSaProList(localDateTime);
                PageInfo<GhostSaPro2> pages12 = new PageInfo<>(ghostSaProList1);
                List<GhostSaPro2> list = pages12.getList();
                List<GhostSaProAllJson2> list1 = new ArrayList<>();
                for (GhostSaPro2 ghostSaPro : list) {
                    String allJson = ghostSaPro.getAllJson();
                    GhostSaProAllJson ghostSaProAllJson = dealJson(allJson, ghostSaPro.getEvent(), localDateTime);
                    GhostSaProAllJson2 ghostSaProAllJson2 = new GhostSaProAllJson2();
                    BeanUtils.copyProperties(ghostSaProAllJson, ghostSaProAllJson2);
                    list1.add(ghostSaProAllJson2);
                }
                log.info("同步账期2：" + localDateTime + " 当前页数/总页数:" + i + "/" + pages1);
                ghostSaProAllJson2Mapper.insert(list1);
                // ghostSaProPgMapper.insert(list);
            }
        }
    }

    public void synccData(List<String> lt) {
        for (String localDateTime : lt) {
            Page<GhostSaPro> ghostSaProList = PageHelper.startPage(1, 1000);
            ghostSaProList = ghostSaProMapper.getGhostSaProList(localDateTime);
            PageInfo<GhostSaPro> pages = new PageInfo<>(ghostSaProList);
            int pages1 = pages.getPages();
            for (int i = 1; i <= pages1; i++) {
                Page<GhostSaPro> ghostSaProList1 = PageHelper.startPage(i, 1000);
                ghostSaProList1 = ghostSaProMapper.getGhostSaProList(localDateTime);
                PageInfo<GhostSaPro> pages12 = new PageInfo<>(ghostSaProList1);
                List<GhostSaPro> list = pages12.getList();
                List<GhostSaProAllJson> list1 = new ArrayList<>();
                for (GhostSaPro ghostSaPro : list) {
                    String allJson = ghostSaPro.getAllJson();
                    list1.add(dealJson(allJson, ghostSaPro.getEvent(), localDateTime));
                }
                log.info("同步账期：" + localDateTime + " 当前页数/总页数:" + i + "/" + pages1);
                ghostSaProAllJsonMapper.insert(list1);
                // ghostSaProPgMapper.insert(list);
            }
        }
    }


    public GhostSaProAllJson dealJson(String allJson, String event, String accountDate) {
        GhostSaProAllJson ghostSaProAllJson = new GhostSaProAllJson();
        JSONObject jsonObject = JSONObject.parseObject(allJson);
        long time = jsonObject.getLongValue("time");
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault());
        JSONObject properties = jsonObject.getJSONObject("properties");
        String os = properties.getString("$os");
        String lib = properties.getString("$lib");
        Boolean wifi = properties.getBoolean("$wifi");
        String brand = properties.getString("$brand");
        String model = properties.getString("$model");
        String app_id = properties.getString("$app_id");
        String app_name = properties.getString("$app_name");
        String lib_method = properties.getString("$lib_method");
        String os_version = properties.getString("$os_version");
        String app_version = properties.getString("$app_version");
        String lib_version = properties.getString("$lib_version");
        Boolean is_first_day = properties.getBoolean("$is_first_day");
        String manufacturer = properties.getString("$manufacturer");
        String network_type = properties.getString("$network_type");
        Integer screen_width = properties.getInteger("$screen_width");
        Integer screen_height = properties.getInteger("$screen_height");
        Integer timezone_offset = properties.getInteger("$timezone_offset");
        String distinct_id = jsonObject.getString("distinct_id");
        String launch_from = properties.getString("launch_from");
        String launch_type = properties.getString("launch_type");
        String action_type = properties.getString("action_type");
        String drama_id = properties.getString("drama_id");
        String channel = properties.getString("channel");
        String play_source = properties.getString("play_source");
        String option = properties.getString("option");
        String ad_position = properties.getString("ad_position");
        String ad_value = properties.getString("ad_value");
        String result = properties.getString("result");
        Integer event_duration = properties.getInteger("event_duration");
        String abtest_experiment_id = properties.getString("$abtest_experiment_id");
        String abtest_experiment_group_id = properties.getString("$abtest_experiment_group_id");
        String media_source = properties.getString("media_source");
        String app_crashed_reason = properties.getString("app_crashed_reason");
        String ad_network = properties.getString("ad_network");
        ghostSaProAllJson.setLaunchFrom(launch_from);
        ghostSaProAllJson.setLaunchType(launch_type);
        ghostSaProAllJson.setActionType(action_type);
        ghostSaProAllJson.setDramaId(drama_id);
        ghostSaProAllJson.setChannel(channel);
        ghostSaProAllJson.setPlaySource(play_source);
        ghostSaProAllJson.setOption(option);
        ghostSaProAllJson.setAdPosition(ad_position);
        ghostSaProAllJson.setAdValue(ad_value);
        ghostSaProAllJson.setResult(result);
        ghostSaProAllJson.setEventDuration(event_duration);
        ghostSaProAllJson.setAbtestExperimentId(abtest_experiment_id);
        ghostSaProAllJson.setAbtestExperimentGroupId(abtest_experiment_group_id);
        ghostSaProAllJson.setMediaSource(media_source);
        ghostSaProAllJson.setLib(lib);
        ghostSaProAllJson.setOs(os);
        ghostSaProAllJson.setWifi(wifi);
        ghostSaProAllJson.setBrand(brand);
        ghostSaProAllJson.setModel(model);
        ghostSaProAllJson.setDistinctId(distinct_id);
        ghostSaProAllJson.setAppId(app_id);
        ghostSaProAllJson.setAppName(app_name);
        ghostSaProAllJson.setLibMethod(lib_method);
        ghostSaProAllJson.setOsVersion(os_version);
        ghostSaProAllJson.setAppVersion(app_version);
        ghostSaProAllJson.setLibVersion(lib_version);
        ghostSaProAllJson.setIsFirstDay(is_first_day);
        ghostSaProAllJson.setManufacturer(manufacturer);
        ghostSaProAllJson.setNetworkType(network_type);
        ghostSaProAllJson.setScreenWidth(screen_width);
        ghostSaProAllJson.setScreenHeight(screen_height);
        ghostSaProAllJson.setTimezoneOffset(timezone_offset);
        ghostSaProAllJson.setCreateDate(localDateTime);
        ghostSaProAllJson.setEvent(event);
        ghostSaProAllJson.setAppCrashedReason(app_crashed_reason);
        ghostSaProAllJson.setAccountDate(accountDate);
        ghostSaProAllJson.setAdNetwork(ad_network);
        return ghostSaProAllJson;
    }


    @Override
    public void moveGhostSaProDeviceData() {
        LocalDateTime localDateTime = LocalDateTime.now().minusDays(1);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String startTime = df.format(localDateTime) + "T00:00:00";
        String endTime = df.format(localDateTime) + "T23:59:59";
        DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME; // 使用ISO格式解析
        LocalDateTime dateTime = LocalDateTime.parse(startTime, formatter);
        LocalDateTime dateTime1 = LocalDateTime.parse(endTime, formatter);
        Instant instant = dateTime.atZone(ZoneId.systemDefault()).toInstant(); // 使用系统默认时区
        Instant instant1 = dateTime1.atZone(ZoneId.systemDefault()).toInstant(); // 使用系统默认时区
        long startTimestamp = instant.toEpochMilli() / 1000;
        long endTimestamp = instant1.toEpochMilli() / 1000;
        QueryWrapper<GhostSaProDevice> queryWrapper = new QueryWrapper<GhostSaProDevice>();
        queryWrapper.ge("created_at", startTimestamp);
        queryWrapper.le("created_at", endTimestamp);
        List<GhostSaProDevice> ghostSaProDevices = ghostSaProDeviceMapper.selectList(queryWrapper);
        System.out.println("大小---->" + ghostSaProDevices.size());

        ghostSaProDevices.forEach(ghostSaProDevice -> {
            try {
                ghostSaProDevicePgMapper.insert(ghostSaProDevice);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        });
    }

    @Override
    public void cleanData() {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String localDateTime = LocalDateTime.now().minusDays(5).format(df);
        QueryWrapper<GhostSaPro> queryWrapper = new QueryWrapper<GhostSaPro>();
        queryWrapper.le("date", localDateTime);
        queryWrapper.last("limit 1000");
        int delete = ghostSaProMapper.delete(queryWrapper);
        log.info("数据清理GhostSaPro：" + delete);

        QueryWrapper<GhostSaPro2> queryWrapper2 = new QueryWrapper<GhostSaPro2>();
        queryWrapper2.le("date", localDateTime);
        queryWrapper2.last("limit 1000");
        int delete1 = ghostSaPro2Mapper.delete(queryWrapper2);
        log.info("数据清理GhostSaPro2：" + delete1);


        String localDateTime1 = LocalDateTime.now().minusDays(30).format(df);
        QueryWrapper<GhostSaProAllJson> queryWrapper3 = new QueryWrapper<GhostSaProAllJson>();
        queryWrapper3.le("account_date", localDateTime1);
        queryWrapper3.last("limit 1000");

        List<GhostSaProAllJson> ghostSaProAllJsons = ghostSaProAllJsonMapper.selectList(queryWrapper3);
        if (ghostSaProAllJsons.size() > 0) {
            List<String> collect = ghostSaProAllJsons.stream().map(GhostSaProAllJson::getDistinctId).collect(Collectors.toList());
            List<String> collect1 = ghostSaProAllJsons.stream().map(GhostSaProAllJson::getAccountDate).collect(Collectors.toList());
            int delete2 = ghostSaProAllJsonMapper.deleteByObj(collect, collect1);
            log.info("数据清理GhostSaProAllJson：" + delete2);
        }

        QueryWrapper<GhostSaProAllJson2> queryWrapper4 = new QueryWrapper<GhostSaProAllJson2>();
        queryWrapper4.le("account_date", localDateTime1);
        queryWrapper4.last("limit 1000");

        List<GhostSaProAllJson2> ghostSaProAllJsons2 = ghostSaProAllJson2Mapper.selectList(queryWrapper4);
        if (ghostSaProAllJsons2.size() > 0) {
            List<String> collect2 = ghostSaProAllJsons2.stream().map(GhostSaProAllJson2::getDistinctId).collect(Collectors.toList());
            List<String> collect3 = ghostSaProAllJsons2.stream().map(GhostSaProAllJson2::getAccountDate).collect(Collectors.toList());
            int delete3 = ghostSaProAllJson2Mapper.deleteByObj(collect2, collect3);
            log.info("数据清理GhostSaProAllJson2：" + delete3);
        }


    }
}

















